
//  How to use :
//  [[UpgradeAlert instance] showUpgradeAlert];
//


#import "UpgradeAlert.h"
#import "SingletonDefine.h"
#import "YoucApi.h"
#import "Util.h"
#import <iOSToast.h>

static NSString *AlertTitle = @"检测到新版本";
static NSString *AlertCancelButtonTitle = @"稍后更新";
static NSString *AlertGoToStoreButtonTitle = @"立即更新";

@interface UpgradeAlert ()

@property (assign) BOOL showManual;

@end

@implementation UpgradeAlert

OBJC_IMPL_SINGLETON(UpgradeAlert);

@synthesize showManual = _showManual;

- (void)showMessage:(NSString *)message
{
	[[Util mainWindow] makeToast:message duration:1.0f position:kDefaultPosition];
}

- (void) startCheck:(BOOL)showManual
{
	if (isAlertActive == NO)
	{
		self.showManual = showManual;
		
		if (self.showManual)
		{
			[self showMessage:@"正在检查新版本"];
		}
		
		NSString *curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
		
		[[YoucApi instance] checkVersion:curVersion context:nil delegate:self];
		
		isAlertActive = YES;
	}
}

- (void) showUpgradeAlert 
{
	[self startCheck:NO];
}

- (void) checkUpgrade
{
	[self startCheck:YES];
}

- (void)versionCheck:(YARespAppVersion*)respAppVersion
{
	if (![NSThread isMainThread])
	{
		[self performSelectorOnMainThread:@selector(versionCheck:) withObject:respAppVersion waitUntilDone:NO];
		return;
	}
	
	NSString * requiredVersion = respAppVersion.version;
	NSString * actualVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
	
	if ([requiredVersion compare:actualVersion options:NSNumericSearch] == NSOrderedDescending) {
		AppUrl = [respAppVersion.appUrl retain];
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: AlertTitle
															message: respAppVersion.description
														   delegate: self
												  cancelButtonTitle: AlertCancelButtonTitle
												  otherButtonTitles: AlertGoToStoreButtonTitle, nil];
		[alertView show];
		[alertView release];
		
	}
	else {
		
		if (self.showManual)
		{
			[self performSelector:@selector(showMessage:) withObject:@"当前版本是最新的" afterDelay:1.0];
		}
		
		isAlertActive = NO;
	}
}

#pragma mark CADelegateClientVersionCheck
- (void)checkVersionResponse:(id)task respAppVersion:(YARespAppVersion *)respAppVersion
{
	[self versionCheck:respAppVersion];
}

- (void) alertView:(UIAlertView *)theAlertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0) 
	{ 
		/* Cancel. Reset date. */
	}
	else if (buttonIndex == 1) 
	{ 
		/* Go to the AppStore. */
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:AppUrl]];
	}
	[AppUrl release];
	isAlertActive = NO;
}

@end